package shopping.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import shopping.web.vo.ResultVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/testjson")
public class JsonServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //这次业务返回你好
//        ResultVo resultVo = new ResultVo();
//        resultVo.setCode(ResultVo.CODE_SUCCESS);
//        resultVo.setData("你好");
//        resultVo.setMessage("正常返回的描述信息");
//        //调用jackson的转换方法
//        String s = new ObjectMapper().writeValueAsString(resultVo);

        //这次返回数组
        ResultVo resultVo = new ResultVo();
        String[] data = new String[]{"小红","小明","小天"};
        resultVo.setCode(ResultVo.CODE_SUCCESS);
        resultVo.setData(data);
        resultVo.setMessage("正常返回的描述信息");
        String s = new ObjectMapper().writeValueAsString(resultVo);

        //返回给客户端
        response.getWriter().print(s);
    }
}
